package com.itheima.business.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.itheima.business.config.SecretProperties;
import com.itheima.response.HttpStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Objects;
@RequiredArgsConstructor
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final SecretProperties secretProperties;

    /*****
     * 用户登录拦截器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1）获取请求头中的令牌
        String token = request.getHeader("token");

        //2)如果令牌为空，或者令牌解析失败，则拦截请求
        if(Objects.isNull(token) || !JWTUtil.verify(token,secretProperties.getJwtBytes())){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        return true;
    }
}